package xyz.jcat.sco.gateway.oauth2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import xyz.jcat.common.util.ArrayUtils;
import xyz.jcat.common.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class ReactiveAuthorizationManagerImpl implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();
        String path = request.getURI().getPath();
        //TODO
        if(ArrayUtils.contains(new String[]{"/sco/admin/oauth2/oauth/token"}, path)) {
            return Mono.just(new AuthorizationDecision(true));
        }
        List<Long> roleIds = getNeedRoleIds(path);
        //不需要认证
        if(CollectionUtils.isEmpty(roleIds)) {
            return Mono.just(new AuthorizationDecision(true));
        }

        return mono.filter(authentication -> authentication.isAuthenticated())
                .flatMapIterable(authentication -> {
                    //TODO 获取 roleId list
                    return Arrays.asList(1L, 2L);
                })
                .any(roleId -> {
                    return roleIds.contains(roleId);
                })
                .map(hasPermission -> new AuthorizationDecision(hasPermission))
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

    public List<Long> getNeedRoleIds(String path) {
        return Arrays.asList(3L);
    }

}
